package org.camunda.bpm.getstarted.loanapproval.listener;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.getstarted.loanapproval.mapper.TicketMapper;
import org.camunda.bpm.getstarted.loanapproval.mapper.TicketTaskMapper;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.TicketTaskDO;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.WorkstationDO;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.WorkstationTaskDO;
import org.camunda.bpm.getstarted.loanapproval.utils.ApplicationContextUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CreateListener implements TaskListener {

    private TicketMapper ticketMapper;

    private TicketTaskMapper ticketTaskMapper;

    public CreateListener() {
        ticketMapper = ApplicationContextUtils.getBeanByClass(TicketMapper.class);
        ticketTaskMapper = ApplicationContextUtils.getBeanByClass(TicketTaskMapper.class);
    }



    @Override
    public void notify(DelegateTask delegateTask) {
        System.out.println("监听器CreateListener=========================================================" + delegateTask.getName());
        // 往tb_ticket_task里面插入一条数据
        Map<String,Object> variables = delegateTask.getVariables();
        TicketTaskDO ticketTaskDO = new TicketTaskDO();
        ticketTaskDO.setTaskId(delegateTask.getId());
        ticketTaskDO.setTicketId((Long)variables.get("ticketId"));
        ticketTaskDO.setCreateTime(new Date());
        ticketTaskDO.setUpdateTime(new Date());
        ticketTaskDO.setPrtyCode(delegateTask.getTaskDefinitionKey());

        ticketTaskDO.setStatus(0);
        ticketTaskMapper.insert(ticketTaskDO);

        // 将任务分配给能处理的工作台
        List<Long> workstationIds = (List<Long>)variables.get("workstationIds");
        if (null == workstationIds) {
            List<WorkstationDO> workstations = ticketTaskMapper.selectWorkstations(delegateTask.getTaskDefinitionKey());
            workstationIds = workstations.stream().map(WorkstationDO::getId).collect(Collectors.toList());
        }
        workstationIds.forEach(w -> {
            WorkstationTaskDO workstationTaskDO = new WorkstationTaskDO();
            workstationTaskDO.setTicketTaskId(ticketTaskDO.getId());
            workstationTaskDO.setWorkstationId(w);
            ticketTaskMapper.insertWorkstationTask(workstationTaskDO);
        });
    }
}
